<template>
	<view class="identity">

		<view class="img-upload">
			<view class="top-tips">
				*请拍摄/上传您本人的身份证件(图片限10M以内)
			</view>
			<view class="flex-space-between">
				<view class="img-upload-item">
					<view class="title">
						身份证人像面证件照
					</view>
					<view class="box-image" @click="chooseImg(1)">
						<image class="bg-image"
							:src="frontIDCardImage ? frontIDCardImage : require('@/common/images/identification/img-id-photo-png.png')"
							mode="aspectFill"></image>
						<view class="add">+</view>
						<view class="bottom">
							点击上传身份证人像面图片
						</view>
					</view>
				</view>
				<view class="img-upload-item">
					<view class="title">
						身份证国徽面证件照
					</view>
					<view class="box-image" @click="chooseImg(2)">
						<image class="bg-image"
							:src="backIDCardImage ? backIDCardImage : require('@/common/images/identification/img-national-emblem-png.png')"
							mode="aspectFill"></image>
						<view class="add">+</view>
						<view class="bottom">
							点击上传身份证国徽面图片
						</view>
					</view>
				</view>
			</view>
			<view class="flex-space-between">
				<!--<view class="img-upload-item">
					<view class="title">
						手持身份证人像面证件照
					</view>
					<view class="box-image" @click="chooseImg(3)">
						<image class="bg-image"
							:src="handImage ? handImage : require('@/common/images/identification/img-id-photo-png.png')"
							mode="aspectFill"></image>
						<view class="add">+</view>
						<view class="bottom">
							点击上传手持身份证人像面证件照
						</view>
					</view>
				</view>-->
				<view class="img-upload-item">
					<view class="title">
						人脸照
					</view>
					<view class="box-image" @click="chooseImg(9)">
						<image class="bg-image"
							:src="liveCheckPhoto ? liveCheckPhoto : require('@/common/images/identification/img-id-photo-png.png')"
							mode="aspectFill"></image>
						<view class="add">+</view>
						<view class="bottom">
							点击上传人脸照
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="form">
			<view class="item">
				<text class="text">姓名</text>
				<input class="input" placeholder="请输入姓名" v-model="form.realName" type="text" />
			</view>
			<view class="item">
				<text class="text">身份证号</text>
				<input class="input" placeholder="请输入身份证号" v-model="form.identityCard" type="text" />
			</view>
			<!-- <view class="item">
				<text class="text">所在地区</text>
				<uni-data-picker split=" " class="area-picker" :localdata="areaData"
					:popup-title="form.areaText ? form.areaText : '请选择城市'" @change="onchange">
					{{ form.idCardAddress }}
				</uni-data-picker>
			</view> -->
			<view class="item">
				<text class="text">详细地址</text>
				<textarea auto-height class="input" placeholder="请输入详细地址" v-model="form.idCardAddress" type="text" />
			</view>
			<view class="item">
				<text class="text">有效期开始日期</text>
				<picker class="input" mode="date" fields="day" :value="form.idCardValidityStart"
					@change="pickerConfirmHandle($event, 1)">
					<view class="uni-input">{{ form.idCardValidityStart ? form.idCardValidityStart : '请选择' }}</view>
				</picker>
			</view>
			<view class="item">
				<text class="text">有效期结束日期</text>
				<picker class="input" mode="date" fields="day" :value="form.idCardValidityEnd"
					@change="pickerConfirmHandle($event, 2)">
					<view class="uni-input">{{ form.idCardValidityEnd ? form.idCardValidityEnd : '请选择' }}</view>
				</picker>
			</view>
			<view class="item">
				<text class="text">终端号</text>
				<input class="input" :disabled="terminalInto" placeholder="请输入终端号" v-model="serialno" type="text" @blur="clearKG" />
				<!-- <image class="icon" @click="scanCode" :src="sanCodeImage" mode=""></image> -->
			</view>
			<view class="tips">
				*我们承诺此信息只用于验证您的身份，我们将严格保管加密您的信息
			</view>
			<view class="next" @click="idCardSubmit">下一步</view>
		</view>

		<w-compress ref="wCompress2" />
	</view>
</template>

<script>
	import areaData from '_c/utils/area2';
	import {
		smsSend,
		getBankCode,
		subBankCode,
		checkPos
	} from '_a/system';
	import {
		informationQuery,
		queryCustomer
	} from '_a/user';
	import uploadImgMixin from '@/mixins/uploadImg';
	// import { editCard, editCardList } from '_a/home';
	import {
		IsCard,
	} from "_c/utils/validate";
	import {
		getProvinceList,
		getProvinceApi
	} from '_a/home';

	export default {
		mixins: [uploadImgMixin],
		props: ["formData", 'sanSerialno', 'res'],
		data() {
			return {
				form: {
					realName: "",
					identityCard: "",
					idCardAddress: "请选择地区",
					idCardValidityEnd: "",
					idCardValidityStart: ""
				},
				type: 1, //1:修改 2:添加
				frontIDCardImage: "",
				backIDCardImage: "",
				handImage: "",
				liveCheckPhoto: "",
				disabled: false,
				areaData: areaData,
				bItem: null, // 失败数据
				sanCodeImage: require('@/common/images/identification/sanCode.png'),
				serialno: '',
				resData: ''
			};
		},
		// watch: {
		// 	res: {
		// 		handler(n, o) {
		// 			console.log(n);
		// 			this.resData = n
		// 		},
		// 		deep: true
		// 	}

		// },
		created() {


		},
		computed: {
			// 是否机具扫码进入
			terminalInto() {
				return this.$store.getters.terminalInto || false
			}
		},
		onLoad(option) {
			// const appAuthorizeSetting = uni.getAppAuthorizeSetting();
			// console.log("appAuthorizeSetting",appAuthorizeSetting.locationAuthorized)
		},
		methods: {
			async loadingInfo() {
				//alert(JSON.stringify(this.res));
				//this.res = await informationQuery();
				const scanSerialno = this.$storage.getStore('serialno');
				this.res = await queryCustomer({scanSerialno});
				if(this.res){
					console.log(1);
					await this.getData();
				}else{
					let idCardFormData = this.$storage.getStore('idCardFormData');
					if (idCardFormData && idCardFormData.edit) {
						console.log(1);
						this.form = {
							...idCardFormData
						}
						this.frontIDCardImage = idCardFormData.frontIDCardImage;
						this.backIDCardImage = idCardFormData.backIDCardImage;
						this.handImage = idCardFormData.handImage;
						this.liveCheckPhoto = idCardFormData.liveCheckPhoto;
						this.serialno = idCardFormData.serialno;
					}
				}
				// 扫码机具进入
				if (this.sanSerialno ) {
				//if (this.sanSerialno && this.terminalInto) {
					this.form.serialno = this.sanSerialno;
					this.serialno = this.sanSerialno;
				}
			},
			clearKG(v) {
				// console.log(v);
				let value = v.detail.value
				if (value.includes(' ')) {
					this.form.serialno = value.replaceAll(/\s/g, "")
				}
			},
			getData() {
				console.log(this.res);
				if (this.res) {
					let res = {}
					res = this.res
					this.frontIDCardImage = res.data.idCardImgFrontPath;
					this.backIDCardImage = res.data.idCardImgBackPath;
					this.handImage = res.data.idCardImgHandPath;
					this.form.realName = res.data.realName;
					this.form.identityCard = res.data.identityCard;
					this.form.idCardAddress = res.data.idCardAddress;
					this.form.idCardValidityStart = res.data.idCardValidityStart;
					this.form.idCardValidityEnd = res.data.idCardValidityEnd;
					this.serialno = res.data.serialno;
					this.form.serialno = res.data.serialno;
					this.liveCheckPhoto = res.data.liveCheckPath;
					// 扫码机具进入
					if (this.sanSerialno && this.terminalInto) {

						this.form.serialno = this.sanSerialno;
						this.serialno = this.sanSerialno;
					}
				}

			},
			getDate(value) {
				if (value == '长期') {
					return value;
				}
				return value.substring(0, 4) + '-' + value.substring(4, 6) + '-' + value.substring(6, 8);
			},
			pickerConfirmHandle(e, type) {
				switch (type) {
					case 1:
						this.form.idCardValidityStart = e.detail.value;
						break;
					case 2:
						this.form.idCardValidityEnd = e.detail.value;
						break;
					default:
						break;
				}
				console.log("this.form", this.form);
			},
			chooseImg(type) {
				let _this = this;
				
				let chooseImgtype = ['album'];
				let otherParams = {}
				if (type == 9) {
					if (!_this.form.realName && !_this.form.identityCard) {
						return _this.$tip.toast('请先上传身份证照或者填写姓名和身份证号!');
					}
					chooseImgtype = ['album'];
					otherParams = {
						realName: _this.form.realName,
						identityCard: _this.form.identityCard
					}
				}
				
				_this.$selectUpload.chooseImg_(chooseImgtype).then(async res => {
					const size = res.tempFiles[0].size;
					// const pixelsValue = size < (1024*1024)?1500000:90000;
					// console.log({pixelsValue});
					_this.$tip.loading('上传中...');
					setTimeout(function() {
						_this.$tip.loaded();
					}, 10000);
					// h5要单独压缩
					// // #ifdef H5
					// if (size > (1024 * 1024*4)) {
					// 	base64 = await this.$refs.wCompress2.start(res.tempFilePaths[0], {
					// 		pixels: 90000, // 最大分辨率，默认二百万
					// 		quality: 0.8, // 压缩质量，默认0.8
					// 		type: 'png', // 图片类型，默认jpg
					// 		base64: true // 是否返回base64，默认false，非H5有效
					// 	});
					// } else {
					// 	base64 = await this.getBase64(res.tempFilePaths[0]);
					// }
					// // #endif
					// // #ifndef H5
					// base64 = await this.getBase64(res.tempFilePaths[0]);
					// // #endif
					// let base64;
					if(size > (1024 * 1024*10)){
						return this.$tip.toast('上传图片不超过10M!');
					}
					// base64 = await this.getBase64(res.tempFilePaths[0]);
					// let ocrInfo = await this.ocrGetInfo(base64, `0${type}`, otherParams);
					const file = res.tempFilePaths[0];
					otherParams.serialno = this.$storage.getStore('serialno');
					let ocrInfo = await this.uploadApiRequest_(file, `0${type}`,otherParams);
					this.$tip.loaded();
					
					if (ocrInfo.code == 200) {
						this.$tip.success('识别成功!');
						switch (type) {
							case 1:
								this.frontIDCardImage = ocrInfo.data.imgUrl;
								this.form.realName = ocrInfo.data.name;
								this.form.identityCard = ocrInfo.data.idCardNo;
								this.form.idCardAddress = ocrInfo.data.address;
								this.handImage = ocrInfo.data.imgUrl;
								break;
							case 2:
								this.backIDCardImage = ocrInfo.data.imgUrl;
								this.form.idCardValidityStart = this.getDate(ocrInfo.data.signStartTime);
								this.form.idCardValidityEnd = this.getDate(ocrInfo.data.signEndTime);
								break;
							case 3:
								this.handImage = ocrInfo.data.imgUrl;
								break;
							case 9:
								this.liveCheckPhoto = ocrInfo.data.imgUrl;
								break;
							default:
								break;
						}
					}else{
						_this.$tip.loaded();
						_this.$tip.toast(ocrInfo.msg);
					}
				}).catch(e => {
					console.log(e);
					//_this.$tip.toast(ocrInfo.msg);
					//_this.$tip.loaded();
				});
			},
			onchange(e) {
				console.log(e);
				let areaObj = e.detail.value[2];
				this.form.idCardAddress = areaObj.provinceName + areaObj.cityName + areaObj.districtName;
				this.$forceUpdate();
			},

			async idCardSubmit() {
				// console.log(this.$store.getters.terminalInto);
				console.log(this.terminalInto);
				if (!this.terminalInto) {
					// 查询机具是否存在
					let checkPosRes = await checkPos({
						serialno: this.serialno
					});
					if (checkPosRes.code == 200) {
						this.form.serialno = this.serialno;
					} else {
						return this.$tip.toast('终端不存在,请核实!');
					}
				}

				// const result = {
				//     "msg": "操作成功",
				//     "code": 200,
				//     "data": "https://brain.baidu.com/face/print/?token=yCdmOlm1dGI6dI6cn2au3V4c"
				// }
				// // 点击功能模块-触发跳转
				// // 以百度url为例子，具体填写你自己要跳转的链接 
				// uni.navigateTo({
				// 	url: '/pages/webview/webview?url=' + result.data
				// 	// page.json定义的路径 传url到webview界面去接收-实现跳转
				// })
				if (!this.frontIDCardImage || !this.backIDCardImage || !this.handImage || !this.liveCheckPhoto) {
					return this.$tip.toast('请上传完整!');
				}
				if (!this.form.realName) {
					return this.$tip.toast('请输入姓名!');
				}
				if (!IsCard(this.form.identityCard)) {
					return this.$tip.toast('请正确输入身份证号!');
				}
				if (!this.form.idCardAddress) {
					return this.$tip.toast('请输入详细地址!');
				}
				if (!this.form.idCardValidityStart) {
					return this.$tip.toast('请输入有效期开始日期!');
				}
				if (!this.form.idCardValidityEnd) {
					return this.$tip.toast('请输入有效期结束日期!');
				}
				if (!this.form.serialno) {
					return this.$tip.toast('请输入终端号!');
				}
				let params = {
					...this.form
				};
				this.$storage.setStore('idCardFormData', {
					...this.form,
					frontIDCardImage: this.frontIDCardImage,
					backIDCardImage: this.backIDCardImage,
					handImage: this.handImage,
					liveCheckPhoto: this.liveCheckPhoto,
					edit: true
				});
				this.$storage.setStore('certificationOcr', params);
				// this.$tip.loading('提交中....');
				uni.$emit("formDataFn", params)
				this.$emit("idCardSubmit", params, 1)
			},
			scanCode() {
				let _this = this;
				uni.scanCode({
					onlyFromCamera: true,
					success: res => {
						console.log('条码内容：' + res.result);
						_this.serialno = res.result;
					}
				});
			},
			// 查询机具是否存在
			getCheckPos(serialno) {
				checkPos({
					serialno
				}).then(res => {
					if (res.code == 200) {
						this.form.serialno = this.serialno;
					}
				})
				this.$forceUpdate();
			},
			// 获取省
			getProvince(list) {
				let dataInfo = {};
				list.forEach((item, index) => {
					let {
						provinceCode,
						provinceName
					} = item;
					if (!dataInfo[provinceCode]) {
						dataInfo[provinceCode] = {
							value: provinceCode,
							text: provinceName,
							children: [],
						};
					}
					dataInfo[provinceCode].children.push(item);
				});
				let newList = Object.values(dataInfo); // list 转换成功的数据
				console.log({
					newList
				});
				return this.getCity(newList);
			},
			// 获取市
			getCity(list) {
				let dataInfoList = {};
				let listAll = []
				list.forEach((itemList, index) => {
					let dataInfo = {};
					let intList = itemList.children.forEach((item, index) => {
						let {
							cityCode,
							cityName
						} = item;
						if (!dataInfo[cityCode]) {
							dataInfo[cityCode] = {
								value: cityCode,
								text: cityName,
								children: [],
							};
						}
						item.value = item.districtCode
						item.text = item.districtName
						dataInfo[cityCode].children.push(item);
					});
					let getCityList = Object.values(dataInfo); // list 转换成功的数据
					itemList.children = [...getCityList]
					listAll.push(itemList)
				});
				console.log({
					listAll
				});
				return listAll
			},
		}
	};
</script>

<style lang="scss">
	.identity {}

	.img-upload {
		background-color: #ffffff;
		padding: R(30px);
		padding-top: 0;

		.top-tips {
			text-align: left;
			font-size: R(20px);
			color: #C7C7C7;
			padding-top: R(40px);
		}

		.img-upload-item {

			.title {
				color: #1E1E20;
				font-size: R(22px);
				font-weight: 500;
				margin: R(20px) R(30px);
				position: relative;
			}

			.title::before {
				content: "";
				position: absolute;
				display: block;
				left: R(-20px);
				width: R(10px);
				height: R(10px);
				background-color: #1E1E20;
				border-radius: R(50%);
				margin-top: R(10px);
			}

			.box-image {
				// background-color: #DFDFE8;
				border-radius: R(10px);
				padding: R(35px) R(55px);
				width: R(338px);
				border: 1px dotted #c7c7c7;
				// height: R(250px);
				margin: 0 auto;
				position: relative;

				.bg-image {
					width: R(227px);
					height: R(116px);
				}

				.add {
					width: R(50px);
					height: R(50px);
					background-color: #3BC3FF;
					border-radius: 50%;
					text-align: center;
					font-size: R(50);
					line-height: R(45px);
					color: #ffffff;
					position: absolute;
					top: 50%;
					left: 50%; //居中
					margin-left: R(-30px);
					margin-top: R(-30px);
				}

				.bottom {
					font-size: R(15px);
					color: #C7C7C7;
					margin-top: R(20px);
				}
			}
		}


		.tips {
			text-align: center;
			margin: R(30px);
			font-size: R(25px);
			color: #1E1E20;
			font-weight: 400;
		}
	}

	.form {
		margin: R(30px) 0;

		.item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 25upx 20upx;
			font-size: 28upx;
			font-weight: 400;
			color: #262626;
			background: #fff;

			.input {
				flex: 1;
				text-align: right;
				margin-left: auto;
				font-size: 28upx;
				color: #7d7d7d;
			}

			.icon {
				width: 46upx;
				height: 46upx;
				margin-left: 20upx;
			}

			.sendCode {
				margin-left: 10upx;
			}
		}


		.next {
			margin: 40upx auto 0;
			width: 581upx;
			height: 80upx;
			line-height: 80upx;
			text-align: center;
			// background: $themeColor;
			// border: 1upx solid $themeColor;
			border-radius: 10upx;
			font-size: 30upx;
			font-weight: 400;
			color: #ffffff;
			background-color: #3BC3FF;
			// border-radius: R(50px);
		}


		.sub-tips {
			padding: 28upx 30upx;
			font-size: 26upx;
			font-weight: 400;
			color: #999999;
		}
	}

	.tips {
		font-size: R(22px);
		color: #A6A6A6;
		margin: R(30px) R(20px);
	}
</style>